package frontend.pages.admin.foreignmanager;

import backend.service.admin.ForeignManagerService;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.admin.ForeignManagerUIModel;
import frontend.pages.admin.base.AbstractManagingForm;
import frontend.components.base.ComponentFactory;
import org.apache.wicket.markup.html.panel.Panel;

public class ForeignManagerForm extends AbstractManagingForm<ForeignManagerUIModel> {

    private static final String RESOURCE_KEY_FIELD_LABEL_FIRST_NAME = "pages.admin.foreignManager.form.firstName";
    private static final String RESOURCE_KEY_FIELD_LABEL_LAST_NAME = "pages.admin.foreignManager.form.lastName";
    private static final String RESOURCE_KEY_FIELD_LABEL_IS_ACTIVE = "pages.admin.foreignManager.form.isActive";
    private static final String RESOURCE_KEY_VALIDATION_SAME_NAME = "validation.form.foreignManager.sameName";

    public ForeignManagerForm(String id, ForeignManagerUIModel foreignManagerUIModel) {
        super(id, foreignManagerUIModel);
    }

    @Override
    protected void constructFormContent() {
        Panel firstNameComponent = ComponentFactory.createTextFieldComponent("firstName", RESOURCE_KEY_FIELD_LABEL_FIRST_NAME, uiModel);
        Panel lastNameComponent = ComponentFactory.createTextFieldComponent("lastName", RESOURCE_KEY_FIELD_LABEL_LAST_NAME, uiModel);
        Panel isActiveComponent = ComponentFactory.createCheckboxComponent("isActive", RESOURCE_KEY_FIELD_LABEL_IS_ACTIVE, uiModel);

        add(firstNameComponent, lastNameComponent, isActiveComponent);
    }

    @Override
    protected void doFormValidation() {
        validateNotEmpty(uiModel.getFirstName(), RESOURCE_KEY_FIELD_LABEL_FIRST_NAME);
        validateNotEmpty(uiModel.getLastName(), RESOURCE_KEY_FIELD_LABEL_LAST_NAME);
        ForeignManagerService foreignManagerService = TimeTrackingWebApplication.getService(ForeignManagerService.class);
        if (uiModel.getFirstName() != null && uiModel.getLastName() != null && firstOrLastNameWasChanged()) {
            if (foreignManagerService.findForeignManagerByFirstAndLastName(uiModel.getFirstName(), uiModel.getLastName()) != null) {
                addGeneralValidationError(RESOURCE_KEY_VALIDATION_SAME_NAME);
            }
        }
    }

    private boolean firstOrLastNameWasChanged() {
        return (false == (uiModel.getFirstName() + uiModel.getLastName()).equals(
                uiModel.getDBModel().getFirstName() + uiModel.getDBModel().getLastName()));
    }

    @Override
    protected Class getResponsePage() {
        return ForeignManagerManagingPage.class;
    }
}
